<template>
  <el-card style="margin-bottom: 32px" v-loading="loading">
    <el-cascader
      v-model="zone"
      :options="zones"
      :props="{ expandTrigger: 'hover', emitPath: false, checkStrictly: true }"
      @change="onZoneChange"
      placeholder="选择分区"
      style="width: 220px; margin-bottom: 16px"
    />
    <div ref="pieChart" style="height: 400px; width: 100%"></div>
    <el-tag size="large" style="float: right; margin-bottom: 15px"> 统计视频数：{{ count }} </el-tag>
  </el-card>
  <el-card>
    <div ref="radarChart" style="height: 550px; width: 100%"></div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import { useApi } from '@/composables/useApi'
import partitionData from '@/assets/partition.json'

const http = useApi()

const pieChart = ref(null)
const radarChart = ref(null)
const count = ref(0)
let myPie = null
let myRadar = null

const zones = partitionData
const zone = ref(0) // 默认选中全站

const loading = ref(false)

const fields = [
  { key: 'view', name: '播放量', max: 900000 },
  { key: 'like', name: '点赞数', max: 30000 },
  { key: 'coin', name: '投币数', max: 8000 },
  { key: 'favorite', name: '收藏数', max: 25000 },
  { key: 'danmaku', name: '弹幕数', max: 11000 },
  { key: 'reply', name: '评论数', max: 2000 },
]

const durationColors = [
  '#e41a1c', // 红
  '#00bfff', // 蓝
  '#ffb347', // 橙
  '#7cfc00', // 绿
  '#8a2be2', // 紫
  '#ff69b4', // 深粉
  '#ffa500', // 橘黄
  '#20b2aa', // 青色
]

function findNodeByTid(nodes, tid) {
  for (const n of nodes) {
    if (n.value === tid) return n
    if (n.children) {
      const found = findNodeByTid(n.children, tid)
      if (found) return found
    }
  }
  return null
}

const fetchAndRender = async () => {
  loading.value = true
  const res = await http.get('/video/getDurationData', { params: { tid: zone.value } })
  loading.value = false
  if (!res || res.code !== 200) return
  const data = res.data
  console.log('数据', res)
  const partitionName = findNodeByTid(zones, zone.value)?.label || '全站'
  count.value = data.map((d) => d.count).reduce((prev, cur) => prev + cur)
  // 饼图
  if (!myPie) myPie = echarts.init(pieChart.value)
  myPie.setOption({
    title: { text: `${partitionName}分区不同时长视频占比`, left: 'center' },
    tooltip: { trigger: 'item', formatter: '{b}: {d}%' },
    legend: { orient: 'vertical', left: 'left', data: data.map((d) => d.duration) },
    series: [
      {
        name: '视频占比',
        type: 'pie',
        radius: '70%',
        center: ['50%', '60%'],
        data: data.map((d) => ({
          name: d.duration,
          value: d.proportion,
        })),
        label: { formatter: '{b}: {d}%' },
      },
    ],
  })

  // 动态计算每个维度的最大值
  const indicators = fields.map((f) => {
    const maxVal = Math.max(...data.map((d) => d[f.key]))
    return {
      name: f.name,
      max: Math.ceil(maxVal * 1.1) || 10, // 加10%余量，最小为10
    }
  })

  // 雷达图
  if (!myRadar) myRadar = echarts.init(radarChart.value)
  myRadar.setOption({
    title: { text: `${partitionName}分区不同时长视频各项指标对比`, left: 'center' },
    tooltip: {},
    legend: {
      data: data.map((d) => d.duration),
      orient: 'vertical',
      right: 10,
      top: 40,
      itemWidth: 18,
      itemHeight: 14,
    },
    radar: {
      indicator: indicators,
      radius: '70%',
      splitNumber: 5,
    },
    series: [
      {
        type: 'radar',
        data: data.map((d, i) => ({
          value: fields.map((f) => d[f.key]),
          name: d.duration,
          lineStyle: { color: durationColors[i % durationColors.length] },
          itemStyle: { color: durationColors[i % durationColors.length] },
          areaStyle: { opacity: 0.08 },
        })),
      },
    ],
  })
}

const onZoneChange = () => {
  fetchAndRender()
}

onMounted(() => {
  fetchAndRender()
  window.addEventListener('resize', () => {
    myPie && myPie.resize()
    myRadar && myRadar.resize()
  })
})
</script>
